<template>
	<view class="profile-page">
		
		<!-- 头像 -->
		<view class="profile-section">
			<view class="profile-item" @click="changeAvatar">
				<view class="item-left">
					<text class="item-label">头像</text>
				</view>
				<view class="item-right">
					<image :src="userInfo.avatar || defaultAvatar" class="avatar-img"></image>
					<u-icon name="arrow-right" color="#999999" size="28"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 基本信息 -->
		<view class="profile-section">
			<view class="profile-item" @click="editField('nickname')">
				<view class="item-left">
					<text class="item-label">昵称</text>
				</view>
				<view class="item-right">
					<text class="item-value">{{ userInfo.nickname || '未设置' }}</text>
					<u-icon name="arrow-right" color="#999999" size="28"></u-icon>
				</view>
			</view>
	
			
			<view class="profile-item" @click="editField('email')">
				<view class="item-left">
					<text class="item-label">邮箱</text>
				</view>
				<view class="item-right">
					<text class="item-value">{{ userInfo.email || '未设置' }}</text>
					<u-icon name="arrow-right" color="#999999" size="28"></u-icon>
				</view>
			</view>
			
				<view class="profile-item" @click="editField('gender')">
					<view class="item-left">
						<text class="item-label">性别</text>
					</view>
					<view class="item-right">
						<text class="item-value">{{ getGenderText(userInfo.gender) }}</text>
						<u-icon name="arrow-right" color="#999999" size="28"></u-icon>
					</view>
				</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-section">
			<button class="save-btn" @click="saveProfile">保存修改</button>
		</view>
	</view>
</template>

<script>
	
	import { baseUrl } from '@/utils/config.js'
	export default {
		data() {
			return {
				userInfo: {},
				defaultAvatar: 'https://www.shuyunpt.com/app/image/default-avatar.png',
				editingField: ''
			}
		},
		onLoad() {
			this.getUserInfo();
		},
		methods: {
			// 获取用户信息
			async getUserInfo() {
				try {
					const res = await this.$service({
						url: "/api/member.user/getUserInfo",
						method: "GET"
					});
					
					if (res.code == 1) {
						this.userInfo = res.data;
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
					this.$hint.desc('获取用户信息失败');
				}
			},
			
			// 格式化手机号
			formatMobile(mobile) {
				if (!mobile) return '';
				return mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			},
			
			// 获取性别文本
			getGenderText(gender) {
				const genderMap = {
					1: '男',
					2: '女',
					0: '保密'
				};
				return genderMap[gender] || '未设置';
			},
			
			// 修改头像
			changeAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						this.uploadAvatar(tempFilePath);
					}
				});
			},
			
			// 上传头像
			async uploadAvatar(filePath) {
				try {
					this.$hint.showLoading('上传中...');
					
					const uploadRes = await uni.uploadFile({
						url: baseUrl +'/api/common/uploadImg',
						filePath: filePath,
						name: 'images',
						header: {
							'Authorization': uni.getStorageSync('token') || ''
						}
					});
					
					const result = JSON.parse(uploadRes.data);
					
					if (result.code == 1) {
						this.userInfo.avatar = result.data.url;
						this.$hint.desc('头像上传成功');
					} else {
						this.$hint.desc(result.msg || '上传失败');
					}
				} catch (error) {
					console.error('上传头像失败:', error);
					this.$hint.desc('上传失败，请重试');
				} finally {
					this.$hint.hideLoading();
				}
			},
			
			// 编辑字段
			editField(field) {
				this.editingField = field;
				
				switch (field) {
					case 'nickname':
						this.editNickname();
						break;
					case 'email':
						this.editEmail();
						break;
					case 'gender':
						this.editGender();
						break;
				}
			},
			
			// 编辑昵称
			editNickname() {
				uni.showModal({
					title: '修改昵称',
					editable: true,
					placeholderText: '请输入昵称',
					content: this.userInfo.nickname || '',
					success: (res) => {
						if (res.confirm && res.content.trim()) {
							this.userInfo.nickname = res.content.trim();
						}
					}
				});
			},
			
			// 编辑邮箱
			editEmail() {
				uni.showModal({
					title: '修改邮箱',
					editable: true,
					placeholderText: '请输入邮箱',
					content: this.userInfo.email || '',
					success: (res) => {
						if (res.confirm && res.content.trim()) {
							// 简单的邮箱验证
							const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
							if (emailRegex.test(res.content.trim())) {
								this.userInfo.email = res.content.trim();
							} else {
								this.$hint.desc('请输入正确的邮箱格式');
							}
						}
					}
				});
			},
			
			// 编辑性别
			editGender() {
				uni.showActionSheet({
					itemList: ['保密', '男', '女'],
					success: (res) => {
						this.userInfo.gender = res.tapIndex;
					}
				});
			},
			
			// 编辑生日
			editBirthday() {
				uni.showDatePicker({
					mode: 'date',
					value: this.userInfo.birthday || new Date().toISOString().split('T')[0],
					success: (res) => {
						this.userInfo.birthday = res.value;
					}
				});
			},
			
			// 保存个人资料
			async saveProfile() {
				try {
					this.$hint.showLoading('保存中...');
					
					const res = await this.$service({
						url: "/api/member.user/profile",
						data: this.userInfo
					});
					
					this.$hint.hideLoading();
					
					if (res.code == 1) {
						this.$hint.desc('保存成功');
						// 更新store中的用户信息
						if(this.userInfo.nickname)
						{
							this.$store.commit('updateUserNickname',this.userInfo.nickname)
						}
						if(this.userInfo.avatar)
						{
							this.$store.commit('updateUserAvatar',this.userInfo.avatar)
						}
					} else {
						this.$hint.desc(res.msg || '保存失败');
					}
				} catch (error) {
					this.$hint.hideLoading();
					console.error('保存个人资料失败:', error);
					this.$hint.desc('保存失败，请重试');
				}
			}
		}
	}
</script>

<style scoped>
	.profile-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 40rpx;
	}
	
	.page-header {
		background-color: #ffffff;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		text-align: center;
	}
	
	.profile-section {
		margin-top: 20rpx;
		background-color: #ffffff;
	}
	
	.profile-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
		background-color: #ffffff;
	}
	
	.profile-item:last-child {
		border-bottom: none;
	}
	
	.item-left {
		display: flex;
		align-items: center;
	}
	
	.item-label {
		font-size: 32rpx;
		color: #333333;
	}
	
	.item-right {
		display: flex;
		align-items: center;
	}
	
	.item-value {
		font-size: 28rpx;
		color: #999999;
		margin-right: 10rpx;
	}
	
	.avatar-img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}
	
	.save-section {
		margin-top: 40rpx;
		padding: 0 30rpx;
	}
	
	.save-btn {
		width: 100%;
		height: 88rpx;
		background-color: #5C65FF;
		color: #ffffff;
		font-size: 32rpx;
		border-radius: 44rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.save-btn::after {
		border: none;
	}
	
	.save-btn:active {
		background-color: #4A52E8;
	}
</style> 